import { render, h, shallowReactive } from 'vue'
import { MessageProps } from "./types"
import MessageConstructor from './Message.vue'
import { CreateMessageProps, MessageContext } from './types'
import useZIndex from '@/hooks/useZIndex'

let seed = 1
const instances: MessageContext[] = shallowReactive([])
export const createMessage = (props: CreateMessageProps) => {
    const { nextZIndex } = useZIndex()
    const container = document.createElement('div')
    const id = `message_${seed++}`
    const destroy = () => {
        // 删除数组中对应的实例
        const idx = instances.findIndex(instance => instance.id === id)
        if (idx === -1) return
        instances.splice(idx, 1)
        render(null, container)
    }
    // 手动删除,实际就是手动调整 visible 的值
    const manualDestroy = () => {
        const instance = instances.find(instance => instance.id === id)
        if (instance) {
            instance.vm.exposed!.visible.value = false
        }
    }
    const newProps = {
        ...props,
        id,
        zIndex: nextZIndex(),
        onDestroy: destroy,

    }
    const vnode = h(MessageConstructor, newProps) // vnode 是虚拟节点
    render(vnode, container) // 将一个 vnode 渲染到 dom节点上

    document.body.appendChild(container.firstElementChild!) // 添加一个 !，它是非空断言操作符，表示这个变量不为null或者undefined
    const vm = vnode.component!
    const instance = {
        id,
        vnode,
        vm,
        props: newProps,
        destroy: manualDestroy,
    }
    instances.push(instance)
    return instance
}

export const getLastInstance = () => {
    return instances.at(-1) // at() 返回该索引位置的元素
}

export const getLastBottomOffset = (id: string) => {
    const idx = instances.findIndex(instance => instance.id === id)

    if (idx <= 0) {
        return 0  // 说明它是第一项
    } else {
        const prev = instances[idx - 1] // 前一项
        return prev.vm.exposed!.bottomOffset.value
    }
}
